package xin.nick.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xin.nick.entity.LoginUser;
import xin.nick.entity.ResultCode;
import xin.nick.entity.SystemUser;
import xin.nick.manager.SystemUserManager;
import xin.nick.util.MyAssert;


/**
 * @author Nick
 * @since 2022/7/21/021
 */
@Component
@Slf4j
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class MyUserDetailsService implements UserDetailsService {

    private final SystemUserManager systemUserManager;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        MyAssert.isTrue(StringUtils.hasLength(username), "username不可为空");
        log.info("用户开始登陆: {}", username);

        return getLoginUserByUsername(username);
    }

    /**
     * 根据用户名获取登录用户信息
     * @param username String
     * @return LoginUser
     */
    private LoginUser getLoginUserByUsername(String username) {
        // 获取用户信息,封装成 UserDetails 对象
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper
                .eq(SystemUser::getUsername, username)
                .eq(SystemUser::getDisabled, false);
        SystemUser systemUser = systemUserManager.getListFirst(systemUserLambdaQueryWrapper);
        MyAssert.notNull(systemUser, ResultCode.ACCOUNT_OR_PASSWORD_ERROR);
        String userPassword = systemUser.getPassword();

        // 返回 UserDetails 对象
        LoginUser loginUser = new LoginUser(username, userPassword);
        loginUser.setUserId(systemUser.getUserId());
        loginUser.setNickname(systemUser.getNickname());
        return loginUser;
    }


}
